package be.music.tool.timer;

import be.music.tool.time.Clock;

public class Timer implements Runnable{

	private Clock clock;
	
	private long startTimeMillis;
	private long previousTime;
	private long currentTime;
	
	private boolean running = false;
	
	public Timer(Clock clock) {
		this.clock = clock;
	}
	
	public void start() {
		
		this.running = true;
		Thread t = new Thread(this);
		t.start();
		
	}
	
	public void stop() {
		this.running = false;
	}

	private void nextCycle() {
		/*TODO: When process hangs, the number of seconds passed since 
		* last cycle should be added to the clock instead of only one tick.
		*/
		clock.tick();
		previousTime = currentTime;
	}
	
	@Override
	public String toString() {
		return clock.toString();
	}

	public Clock getClock() {
		return this.clock;
	}

	@Override
	public void run() {

		startTimeMillis = System.currentTimeMillis();
		previousTime = startTimeMillis/1000;
		currentTime = 0;
		long timeDifference = 0;
		
		while(running) {
			
			currentTime = System.currentTimeMillis()/1000;
			timeDifference = currentTime - previousTime;
			
			if(timeDifference > 0) {
				nextCycle();
			}
			
			try {
				Thread.sleep(30);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
}
